import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:seedfour/app/services/api_service.dart';

import '../../../models/raw_data.dart';
import '../../../models/seal_detail_entity.dart';
import '../../../remote/request.dart';
import 'state.dart';

class SealDetailLogic extends GetxController {
  final SealDetailState state = SealDetailState();

  final apiService = Get.find<ApiService>();

  @override
  void onInit() {
    super.onInit();

    state.sealId = Get.arguments;

    _getSealDetail();
  }

  void cancelSeal() => request(
        () async {
          await apiService.cancelSeal(state.sealId);
          Get.back(result: true);
        },
        showLoading: true,
      );

  // 下载附件
  void downloadFile(SealAttachFile file) async {
    EasyLoading.show(status: '文件下载中...');

    Directory? appDocDir = await getDownloadsDirectory();
    String savePath = '${appDocDir!.path}/${file.name}';

    RawData? result = await apiService.download(file.id!, state.sealId,
        type: 'apply-delivery');
    if (result != null) {
      var url = result.value['data']['tempPath'];
      final response = await Dio().download(url, savePath);

      if (response.statusCode == 200) {
        EasyLoading.showToast('文件已保存到：$savePath',
            duration: const Duration(seconds: 6));
      } else {
        EasyLoading.showToast('下载失败');
      }
    }
  }

  void _getSealDetail() {
    state.isLoading.value = true;

    apiService.getSealDetail(state.sealId).then((value) => {
          state.isLoading.value = false,
          if (value != null)
            {
              state.sealDetail.value = value,
              state.canCancel.value = value.commonApply!.status! < 2,
              state.caseInfo.value = value.caseInfo,
              _setApproveList(value.approveList!),
            }
        });
  }

  void _setApproveList(List<SealApproveRecord> approveList) {
    state.sealApproveList.clear();
    state.sealApproveList.addAll(approveList);
  }
}
